package wp.ggt.com.wpview.activity;

import android.content.pm.PackageInfo;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
import wp.ggt.com.wpview.R;
import wp.ggt.com.wpview.adapter.RecycleAdapter;
import wp.ggt.com.wpview.bean.AppInfo;

public class RxJavaActivity extends BaseActivity {
    // private SwipeRefreshLayout swipeRefreshLayout;
    private RecyclerView recyclerView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rx_java);
        recyclerView = (RecyclerView) findViewById(R.id.recycle);
        Observable.create(new Observable.OnSubscribe<List<AppInfo>>() {
            @Override
            public void call(Subscriber<? super List<AppInfo>> subscriber) {
                subscriber.onNext(getData());
                subscriber.onCompleted();
            }
        }).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Action1<List<AppInfo>>() {
            @Override
            public void call(List<AppInfo> appInfos) {
                recyclerView.setLayoutManager(new LinearLayoutManager(RxJavaActivity.this));
                recyclerView.setAdapter(new RecycleAdapter(RxJavaActivity.this, appInfos));
            }
        });
    }

    public List<AppInfo> getData() {
        List<AppInfo> datas = new ArrayList<>();
        List<PackageInfo> installedPackages = getPackageManager().getInstalledPackages(0);
        for (PackageInfo info : installedPackages) {
            String name = (String) info.applicationInfo.loadLabel(getPackageManager());
            Drawable drawable = info.applicationInfo.loadIcon(getPackageManager());
            AppInfo appInfo = new AppInfo(drawable, name);
            datas.add(appInfo);
        }
        return datas;
    }
}
